package com.itx.gatewayx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itx.gatewayx.domain.AIConversation;
import com.itx.gatewayx.domain.AIMessage;
import com.itx.gatewayx.domain.AIModel;
import com.itx.gatewayx.domain.dto.AIChatRequest;
import com.itx.gatewayx.domain.dto.AIChatResponse;
import com.itx.gatewayx.mapper.AIConversationMapper;
import com.itx.gatewayx.mapper.AIMessageMapper;
import com.itx.gatewayx.mapper.AIModelMapper;
import com.itx.gatewayx.service.AIService;
import com.itx.gatewayx.utils.DashScopeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * AI服务实现类
 */
@Slf4j
@Service
public class AIServiceImpl implements AIService {

    @Autowired
    private AIMessageMapper aiMessageMapper;
    
    @Autowired
    private AIConversationMapper aiConversationMapper;
    
    @Autowired
    private AIModelMapper aiModelMapper;
    
    @Autowired
    private DashScopeUtils dashScopeUtils;
    
    @Value("${ai.default-model:deepseek-r1}")
    private String defaultModelId;
    
    /**
     * 发送AI对话消息
     */
    @Override
    @Transactional
    public AIChatResponse sendMessage(Long userId, AIChatRequest request) {
        // 获取或创建会话
        AIConversation conversation;
        if (request.getConversationId() != null) {
            conversation = aiConversationMapper.selectById(request.getConversationId());
            // 验证会话所属
            if (conversation == null || (userId != null && !userId.equals(conversation.getUserId()))) {
                conversation = createConversation(userId, request.getModelId());
            }
        } else {
            conversation = createConversation(userId, request.getModelId());
        }
        
        // 保存用户消息
        AIMessage userMessage = AIMessage.builder()
                .conversationId(conversation.getId())
                .userId(userId)
                .role("user")
                .content(request.getMessage())
                .sessionKey(conversation.getSessionKey())
                .modelId(conversation.getModelId())
                .createTime(new Date())
                .updateTime(new Date())
                .deleted(0)
                .build();
        aiMessageMapper.insert(userMessage);
        
        // 获取上下文消息
        List<AIMessage> contextMessages;
        
        // 优先使用客户端传递的历史消息
        if (request.getHistory() != null && !request.getHistory().isEmpty()) {
            contextMessages = new ArrayList<>(request.getHistory());
            // 确保最后一条是当前用户消息
            contextMessages.add(userMessage);
        } else {
            // 从数据库获取最近的10条消息
            contextMessages = getContextMessages(conversation.getId(), 10);
        }
        
        // 调用AI接口获取回复
        String aiReply = callAIService(contextMessages, conversation.getModelId());
        
        // 保存AI回复
        AIMessage aiMessage = AIMessage.builder()
                .conversationId(conversation.getId())
                .userId(userId)
                .role("assistant")
                .content(aiReply)
                .sessionKey(conversation.getSessionKey())
                .modelId(conversation.getModelId())
                .createTime(new Date())
                .updateTime(new Date())
                .deleted(0)
                .build();
        aiMessageMapper.insert(aiMessage);
        
        // 更新会话时间
        conversation.setUpdateTime(new Date());
        if (conversation.getTitle() == null || conversation.getTitle().isEmpty() || "新对话".equals(conversation.getTitle())) {
            // 根据第一条消息自动生成标题
            conversation.setTitle(generateTitle(request.getMessage()));
        }
        aiConversationMapper.updateById(conversation);
        
        // 构建响应
        return AIChatResponse.builder()
                .id(aiMessage.getId())
                .conversationId(conversation.getId())
                .role(aiMessage.getRole())
                .content(aiMessage.getContent())
                .modelId(aiMessage.getModelId())
                .createTime(aiMessage.getCreateTime())
                .build();
    }
    
    /**
     * 获取用户的对话历史
     */
    @Override
    public Page<AIMessage> getConversationHistory(Long userId, Integer page, Integer pageSize) {
        Page<AIMessage> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<AIMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AIMessage::getUserId, userId)
                .eq(AIMessage::getDeleted, 0)
                .orderByDesc(AIMessage::getCreateTime);
        return aiMessageMapper.selectPage(pageParam, queryWrapper);
    }
    
    /**
     * 获取指定会话的消息列表
     */
    @Override
    public List<AIMessage> getMessagesByConversationId(Long conversationId, Long userId) {
        LambdaQueryWrapper<AIMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AIMessage::getConversationId, conversationId)
                .eq(userId != null, AIMessage::getUserId, userId)
                .eq(AIMessage::getDeleted, 0)
                .orderByAsc(AIMessage::getCreateTime);
        return aiMessageMapper.selectList(queryWrapper);
    }
    
    /**
     * 创建新的对话会话
     */
    @Override
    @Transactional
    public AIConversation createConversation(Long userId, String modelId) {
        // 如果未指定模型，使用默认模型
        if (modelId == null || modelId.isEmpty()) {
            modelId = defaultModelId;
        }
        
        // 创建会话
        AIConversation conversation = AIConversation.builder()
                .userId(userId)
                .title("新对话")
                .sessionKey(UUID.randomUUID().toString())
                .modelId(modelId)
                .status(0)
                .createTime(new Date())
                .updateTime(new Date())
                .deleted(0)
                .build();
        aiConversationMapper.insert(conversation);
        return conversation;
    }
    
    /**
     * 获取所有可用的AI模型
     */
    @Override
    public List<AIModel> getAvailableModels() {
        LambdaQueryWrapper<AIModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AIModel::getStatus, 1)
                .eq(AIModel::getDeleted, 0);
        return aiModelMapper.selectList(queryWrapper);
    }
    
    /**
     * 设置用户当前使用的AI模型
     */
    @Override
    public boolean setUserModel(Long userId, String modelId) {
        // 验证模型是否存在
        LambdaQueryWrapper<AIModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AIModel::getModelKey, modelId)
                .eq(AIModel::getStatus, 1)
                .eq(AIModel::getDeleted, 0);
        AIModel model = aiModelMapper.selectOne(queryWrapper);
        
        if (model == null) {
            return false;
        }
        
        // 这里可以保存用户的模型偏好设置
        // 简化实现，仅返回成功
        return true;
    }
    
    /**
     * 删除指定的消息
     */
    @Override
    public boolean deleteMessage(Long messageId, Long userId) {
        LambdaQueryWrapper<AIMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AIMessage::getId, messageId)
                .eq(userId != null, AIMessage::getUserId, userId);
        
        AIMessage message = aiMessageMapper.selectOne(queryWrapper);
        if (message == null) {
            return false;
        }
        
        message.setDeleted(1);
        return aiMessageMapper.updateById(message) > 0;
    }
    
    /**
     * 清空用户的所有对话历史
     */
    @Override
    @Transactional
    public boolean clearHistory(Long userId) {
        // 逻辑删除用户的所有消息
        LambdaQueryWrapper<AIMessage> messageQueryWrapper = new LambdaQueryWrapper<>();
        messageQueryWrapper.eq(AIMessage::getUserId, userId)
                .eq(AIMessage::getDeleted, 0);
        
        List<AIMessage> messages = aiMessageMapper.selectList(messageQueryWrapper);
        for (AIMessage message : messages) {
            message.setDeleted(1);
            aiMessageMapper.updateById(message);
        }
        
        // 逻辑删除用户的所有会话
        LambdaQueryWrapper<AIConversation> conversationQueryWrapper = new LambdaQueryWrapper<>();
        conversationQueryWrapper.eq(AIConversation::getUserId, userId)
                .eq(AIConversation::getDeleted, 0);
        
        List<AIConversation> conversations = aiConversationMapper.selectList(conversationQueryWrapper);
        for (AIConversation conversation : conversations) {
            conversation.setDeleted(1);
            aiConversationMapper.updateById(conversation);
        }
        
        return true;
    }
    
    /**
     * 获取上下文消息
     */
    private List<AIMessage> getContextMessages(Long conversationId, int limit) {
        LambdaQueryWrapper<AIMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AIMessage::getConversationId, conversationId)
                .eq(AIMessage::getDeleted, 0)
                .orderByDesc(AIMessage::getCreateTime)
                .last("LIMIT " + limit);
        
        List<AIMessage> messages = aiMessageMapper.selectList(queryWrapper);
        Collections.reverse(messages); // 按时间正序排列
        return messages;
    }
    
    /**
     * 调用AI服务获取回复
     */
    private String callAIService(List<AIMessage> contextMessages, String modelId) {
        try {
            log.info("调用AI服务，模型：{}，上下文消息数：{}", modelId, contextMessages.size());
            
            // 使用阿里云百炼API获取回复（流式调用）
            return dashScopeUtils.chatStream(contextMessages)
                .get(); // 等待异步调用完成并获取结果
        } catch (Exception e) {
            log.error("调用AI服务失败", e);
            return "抱歉，AI服务暂时不可用，请稍后再试。";
        }
    }
    
    /**
     * 根据消息自动生成会话标题
     */
    private String generateTitle(String message) {
        // 简化实现，取消息的前10个字符作为标题
        if (message.length() <= 10) {
            return message;
        } else {
            return message.substring(0, 10) + "...";
        }
    }
} 